package com.mingye.listener;

import com.mingye.board.Board;
import com.mingye.board.BoardLoader;
import com.mingye.components.BoardPanel;
import com.mingye.components.GameFrame;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/**
 * 选择关卡事件
 *
 * @author daixinyi
 */
public class SelectRoundItemListener implements ItemListener {

    private GameFrame gameFrame;

    public SelectRoundItemListener(GameFrame gameFrame) {
        this.gameFrame = gameFrame;
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            String selectItem = (String) e.getItem();
            Class clazz = BoardLoader.getValueByKey(selectItem);
            if (clazz != null) {
                try {
                    Board board = (Board) clazz.newInstance();
                    BoardPanel boardPanel = gameFrame.getBoardPanel();

                    board.setBoardPanel(boardPanel);
                    boardPanel.setBoard(board);
                    boardPanel.repaint();

                    gameFrame.setVictoryFlag(false);
                    gameFrame.getOperationPanel().getWinInfoLabel().setText("");
                } catch (InstantiationException ex) {
                    throw new RuntimeException(ex);
                } catch (IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }
}
